/**
 * 初始化坐标与表格
 */
let x = 0
let y = 0
let trList = []
let tableList = []

/**
 * 获取焦点
 */
window.addEventListener('click', () => {
    if (isTable()) {
        /**
         * 获取整表模型
         */
        const table = document.activeElement.parentElement.parentElement.parentElement.parentElement
        trList = table.getElementsByTagName('tr')
        tableList = initData(trList)

        /**
         * 获取当前坐标
         */
        x = getCurrentLocation(document.activeElement.parentElement)
        y = getCurrentLocation(document.activeElement.parentElement.parentElement)
    }
})

/**
 * 判断是否为表格
 */
function isTable() {
    if (document.activeElement.tagName === 'INPUT') {
        if (document.activeElement.parentElement.tagName === 'TD') {
            if (document.activeElement.parentElement.parentElement.tagName === 'TR') {
                return true
            }
        }
    }
    return false
}

/**
 * 获取当前坐标
 */
function getCurrentLocation(item) {
    let before = 0
    while (item.previousElementSibling !== null) {
        item = item.previousElementSibling
        before++
    }
    return before
}

/**
 * 初始化表格
 */
function initData(trList) {
    let index = 0
    let tableList = []
    for (const tr of trList) {
        const tdList = tr.getElementsByTagName('td')
        tableList.push([])
        for (const td of tdList) {
            const inputList = td.getElementsByTagName('input')
            for (const input of inputList) {
                tableList[index].push(input)
            }
        }
        index++
    }
    return tableList
}

/**
 * 触发按键
 */
window.addEventListener('keydown', (event) => {
    if (isTable()) {
        switch (event.key) {
            /**
             * 上
             */
            case "ArrowUp":
                if (y > 0) {
                    y--
                }
                break
            /**
             * 右
             */
            case "ArrowRight":
                if (x < tableList[y].length - 1) {
                    x++
                }
                break
            /**
             * 下
             */
            case "ArrowDown":
                if (y < trList.length - 1) {
                    y++
                }
                break
            /**
             * 左
             */
            case "ArrowLeft":
                if (x > 0) {
                    x--
                }
                break
        }
        tableList[y][x].focus()
    }
})
